# from flask_socketio import emit, join_room, leave_room
from flask import session
from flask_socketio import join_room, send, emit

from apps import socketio
from apps.message.messageService import getTrailerAllMessageByIDService, sendMessage


# 前端连接后端
@socketio.on('frontConnect')
def front_connect(data):
    user_ID = data['user_ID']
    trailer_ID = data['trailer_ID']
    room_name = trailer_ID + "_" + user_ID
    join_room(room_name)



# app连接后端
@socketio.on('appConnect')
def app_connect(data):
    user_ID = data['user_ID']
    trailer_ID = data['trailer_ID']
    room_name = trailer_ID + "_" + user_ID
    join_room(room_name)



# 前端发送信息给APP
@socketio.on('frontText')
def front_text(data):
    trailer_ID = data['trailer_ID']
    user_ID = data['user_ID']
    message = data['message_content']
    room_name = trailer_ID + "_" + user_ID
    # join_room(room_name)
    emit('toAppMessage', {'msg': message, "sender": "zhk001"}, room=room_name)
    print(data)
    sendMessage({"sender": user_ID, "receiver": trailer_ID, "message_content": message})

# app发送信息给前端
@socketio.on('appText')
def app_text(data):
    trailer_ID = data['trailer_ID']
    user_ID = data['user_ID']
    message = data['message_content']
    room_name = trailer_ID + "_" + user_ID
    # join_room(room_name)
    emit('toFrontMessage', {'msg': message}, room=room_name)
    sendMessage({"sender": trailer_ID, "receiver": user_ID, "message_content": message})
    # emit('toAppMessage', {"sender": "zhk001", 'msg': "echo"}, room=room_name)



